#include "../zhelpers.h"
#include "front_thread.h"
#include "front_server.h"
#include "proto.msg.pb.h"
#include "Log.h"
#include "vs_opencv.h"

int front_thread::thread_func()
{
	if(get_thread_pool() == NULL){
		LOG_ERROR_VA("[%s] pool_work_thread don't belong to a thread_pool", get_server()->get_name());
		return -1;
	}
	void *receiver = zmq_socket(get_thread_pool()->get_zmq(), ZMQ_REP);
	zmq_connect(receiver, "inproc://workers");
	while(!(get_thread_pool()->has_stoped())){
		//Wait for request from client
		int size;
		zmq_msg_t recv_msg;
		zmq_msg_init(&recv_msg);

		LOG_DEBUG_VA("start recv...");
		size = zmq_recvmsg(receiver, &recv_msg, 0);
		if (size == -1) {
			LOG_ERROR_VA("zmq_recvmsg error");
			send_error_reply(receiver);
			continue;
		}
		string proto_buf;
		proto_buf.assign((char *)zmq_msg_data(&recv_msg), size);
		proto::front_req proto_msg;
		if(!proto_msg.ParseFromString(proto_buf)){
			LOG_ERROR_VA("ParseFromString fail");
			send_error_reply(receiver);
			continue;
		}
		LOG_DEBUG_VA("recv length: %d, class_id: %d", size, proto_msg.class_id());
		//sleep(1);
		//the work of engine
		char *path_buf = (char *)malloc(proto_msg.image_data().size());
		memcpy(path_buf, proto_msg.image_data().c_str(), proto_msg.image_data().size());
		IplImage *ipl = cv_load_image(path_buf, proto_msg.image_size());
		delete [] path_buf;
		if(ipl == NULL){
			LOG_ERROR_VA("open_cv load error");
			send_error_reply(receiver);
			continue;
		}
		send_error_reply(receiver);
	}
	LOG_INFO_VA("[%s] stoped",get_server()->get_name());
	zmq_close(receiver);
	return 0;
}


